package oauth2.config;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import feign.RequestInterceptor;
import feign.RequestTemplate;


/**
 * feign远程调用传递Access-token
 *
 * @author monxz
 * @Date  2020-11-1710:27:23
 * @Des
 *
 */

@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
	@Override
	public void apply(RequestTemplate template) {
		System.err.println("==feingn===");
		HttpServletRequest httpServletRequest = getHttpServletRequest();
		//设置feign传递的请求头
		if (httpServletRequest != null) {			
			Map<String, String> headers = getHeaders(httpServletRequest);
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				template.header(entry.getKey(), entry.getValue());
			}
		}
		//设置feign传递的param
		Enumeration<String> bodyNames = httpServletRequest.getParameterNames();
		StringBuffer body =new StringBuffer();
        if (bodyNames != null) {
            while (bodyNames.hasMoreElements()) {
                String name = bodyNames.nextElement();
                String values = httpServletRequest.getParameter(name);
                body.append(name).append("=").append(values).append("&");
            }
        }
        if(body.length()!=0) {
            body.deleteCharAt(body.length()-1);
            template.body(body.toString());      
        }
		
	}

	private HttpServletRequest getHttpServletRequest() {
		try {
			return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取原请求头
	 */
	private Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> map = new LinkedHashMap<>();
		Enumeration<String> enumeration = request.getHeaderNames();
		if (enumeration != null) {
			while (enumeration.hasMoreElements()) {
				String key = enumeration.nextElement();
				String value = request.getHeader(key);
				map.put(key, value);
			}
		}
		return map;
	}
	
	
}